<template>
  <Dialog
    :visible="visible"
    modal
    header="新增流程定义"
    :style="{ width: '900px', maxHeight: '90vh' }"
    :closable="true"
    :draggable="false"
    @update:visible="$emit('update:visible', $event)"
    @hide="handleClose"
  >
    <div class="definition-form-wizard">
      <!-- 步骤导航 -->
      <div class="steps-container">
        <div 
          v-for="(step, index) in steps" 
          :key="step.id"
          class="step-item"
          :class="{ 
            'active': currentStep === index, 
            'completed': index < currentStep,
            'disabled': index > currentStep
          }"
        >
          <div class="step-number">
            <i v-if="index < currentStep" class="pi pi-check"></i>
            <span v-else>{{ index + 1 }}</span>
          </div>
          <div class="step-info">
            <div class="step-title">{{ step.title }}</div>
            <div class="step-description">{{ step.description }}</div>
          </div>
        </div>
      </div>

      <!-- 步骤内容 -->
      <div class="step-content">
        <!-- 第一步：基本信息 -->
        <div v-show="currentStep === 0" class="step-panel">
          <h3 class="panel-title">基本信息</h3>
          <div class="form-row">
            <div class="form-item">
              <label class="form-label required">流程名称</label>
              <InputText
                v-model="formData.name"
                placeholder="请输入流程名称"
                :class="{ 'p-invalid': errors.name }"
              />
              <small v-if="errors.name" class="p-error">{{ errors.name }}</small>
            </div>
            
            <div class="form-item">
              <label class="form-label required">模型标识</label>
              <InputText
                v-model="formData.modelKey"
                placeholder="请输入模型标识(英文)"
                :class="{ 'p-invalid': errors.modelKey }"
              />
              <small v-if="errors.modelKey" class="p-error">{{ errors.modelKey }}</small>
            </div>
          </div>

          <div class="form-row">
            <div class="form-item">
              <label class="form-label required">流程分类</label>
              <Dropdown
                v-model="formData.categoryId"
                :options="categoryOptions"
                option-label="label"
                option-value="value"
                placeholder="请选择流程分类"
                size="small"
                :class="{ 'p-invalid': errors.categoryId }"
              />
              <small v-if="errors.categoryId" class="p-error">{{ errors.categoryId }}</small>
            </div>
            
          </div>
        </div>

        <!-- 第二步：流程变量 -->
        <div v-show="currentStep === 1" class="step-panel">
          <h3 class="panel-title">流程变量配置</h3>
          <div class="variables-container">
            <div class="variables-header">
              <Button
                icon="pi pi-plus"
                label="添加变量"
                size="small"
                @click="addVariable"
              />
            </div>
            
            <div class="variables-list">
              <div 
                v-for="(variable, index) in formData.variables" 
                :key="index"
                class="variable-item"
              >
                <div class="variable-fields">
                  <div class="variable-field">
                    <label>变量名</label>
                    <InputText
                      v-model="variable.name"
                      placeholder="变量名(英文)"
                      size="small"
                    />
                  </div>
                  <div class="variable-field">
                    <label>变量类型</label>
                    <Dropdown
                      v-model="variable.type"
                      :options="variableTypes"
                      option-label="label"
                      option-value="value"
                      placeholder="请选择类型"
                      size="small"
                    />
                  </div>
                  <div class="variable-field">
                    <label>默认值</label>
                    <InputText
                      v-model="variable.defaultValue"
                      placeholder="默认值"
                      size="small"
                    />
                  </div>
                  <div class="variable-field">
                    <label>描述</label>
                    <InputText
                      v-model="variable.description"
                      placeholder="变量描述"
                      size="small"
                    />
                  </div>
                  <div class="variable-actions">
                    <Button
                      icon="pi pi-trash"
                      severity="danger"
                      text
                      size="small"
                      @click="removeVariable(index)"
                    />
                  </div>
                </div>
              </div>
              
              <div v-if="formData.variables.length === 0" class="empty-variables">
                <i class="pi pi-info-circle"></i>
                <span>暂无流程变量，点击上方"添加变量"按钮添加</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 第三步：流程设计 -->
        <div v-show="currentStep === 2" class="step-panel">
          <h3 class="panel-title">流程设计</h3>
          <div class="bpmn-designer-container">
            <div class="designer-toolbar">
              <Button
                icon="pi pi-pencil"
                label="打开流程设计器"
                size="large"
                @click="openBpmnDesigner"
              />
              <Button
                v-if="formData.modelXml"
                icon="pi pi-eye"
                label="预览XML"
                size="small"
                severity="secondary"
                @click="toggleXmlPreview"
              />
            </div>
            
            <div class="designer-preview">
              <div v-if="!formData.modelXml" class="designer-placeholder">
                <i class="pi pi-sitemap" style="font-size: 3rem; color: #ccc;"></i>
                <p>暂未设计流程</p>
                <p class="placeholder-hint">点击"打开流程设计器"开始设计您的业务流程</p>
              </div>
              
              <div v-else-if="showXmlPreview" class="xml-preview">
                <div class="preview-header">
                  <h4>流程XML预览</h4>
                  <Button
                    icon="pi pi-times"
                    text
                    size="small"
                    @click="showXmlPreview = false"
                  />
                </div>
                <Textarea
                  v-model="formData.modelXml"
                  :rows="15"
                  :auto-resize="false"
                  class="xml-editor"
                  readonly
                />
              </div>
              
              <div v-else class="designer-success">
                <i class="pi pi-check-circle" style="font-size: 3rem; color: #52c41a;"></i>
                <p>流程设计已完成</p>
                <p class="success-hint">可以点击"打开流程设计器"重新编辑，或点击"预览XML"查看流程定义</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- BPMN设计器弹窗 -->
    <BpmnDesigner
      v-model:visible="bpmnDesignerVisible"
      :initial-xml="formData.modelXml"
      @save="handleBpmnSave"
      @close="bpmnDesignerVisible = false"
    />

    <template #footer>
      <div class="dialog-footer">
        <Button
          v-if="currentStep > 0"
          label="上一步"
          severity="secondary"
          icon="pi pi-chevron-left"
          @click="prevStep"
          :disabled="loading"
        />
        <Button
          label="取消"
          severity="secondary"
          @click="handleClose"
          :disabled="loading"
        />
        <Button
          v-if="currentStep < steps.length - 1"
          label="下一步"
          severity="primary"
          icon="pi pi-chevron-right"
          icon-pos="right"
          @click="nextStep"
          :disabled="loading"
        />
        <Button
          v-else
          label="完成"
          severity="primary"
          icon="pi pi-check"
          @click="handleSubmit"
          :loading="loading"
        />
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import Dialog from 'primevue/dialog'
import Button from 'primevue/button'
import InputText from 'primevue/inputtext'
import Dropdown from 'primevue/dropdown'
import Textarea from 'primevue/textarea'
import BpmnDesigner from '../../../../components/BpmnDesigner/EnhancedBpmnDesigner.vue'

interface Props {
  visible: boolean
  categoryOptions?: any[]
  loading?: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit', data: any): void
  (e: 'close'): void
}

const props = withDefaults(defineProps<Props>(), {
  categoryOptions: () => [],
  loading: false
})

const emit = defineEmits<Emits>()

// 步骤配置
const steps = [
  { id: 'basic', title: '基本信息', description: '填写流程基本信息' },
  { id: 'variables', title: '流程变量', description: '配置流程变量' },
  { id: 'design', title: '流程设计', description: 'BPMN流程设计' }
]

// 当前步骤
const currentStep = ref(0)

// BPMN设计器状态
const bpmnDesignerVisible = ref(false)
const showXmlPreview = ref(false)

// 表单数据
const formData = reactive({
  name: '',
  modelKey: '',
  categoryId: null as number | null,
  modelXml: '',
  variables: [] as Array<{
    name: string
    type: string
    defaultValue: string
    description: string
  }>
})

// 表单验证错误
const errors = reactive({
  name: '',
  modelKey: '',
  categoryId: ''
})

// 变量类型选项
const variableTypes = [
  { label: '字符串', value: 'string' },
  { label: '整数', value: 'integer' },
  { label: '浮点数', value: 'double' },
  { label: '布尔值', value: 'boolean' },
  { label: '日期', value: 'date' },
  { label: 'JSON', value: 'json' }
]

// BPMN画布引用

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    resetForm()
  }
})

// 重置表单
const resetForm = () => {
  currentStep.value = 0
  
  Object.assign(formData, {
    name: '',
    modelKey: '',
    categoryId: null,
    modelXml: '',
    variables: []
  })
  
  Object.keys(errors).forEach(key => {
    errors[key as keyof typeof errors] = ''
  })
}

// 添加变量
const addVariable = () => {
  formData.variables.push({
    name: '',
    type: 'string',
    defaultValue: '',
    description: ''
  })
}

// 删除变量
const removeVariable = (index: number) => {
  formData.variables.splice(index, 1)
}

// 验证当前步骤
const validateCurrentStep = () => {
  if (currentStep.value === 0) {
    return validateBasicInfo()
  }
  return true
}

// 验证基本信息
const validateBasicInfo = () => {
  let isValid = true
  
  // 重置错误信息
  Object.keys(errors).forEach(key => {
    errors[key as keyof typeof errors] = ''
  })
  
  // 流程名称验证
  if (!formData.name.trim()) {
    errors.name = '请输入流程名称'
    isValid = false
  } else if (formData.name.length < 2) {
    errors.name = '流程名称至少2个字符'
    isValid = false
  }
  
  // 模型标识验证
  if (!formData.modelKey.trim()) {
    errors.modelKey = '请输入模型标识'
    isValid = false
  } else if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(formData.modelKey)) {
    errors.modelKey = '模型标识只能包含字母、数字和下划线，且必须以字母或下划线开头'
    isValid = false
  }
  
  // 流程分类验证
  if (!formData.categoryId) {
    errors.categoryId = '请选择流程分类'
    isValid = false
  }
  
  return isValid
}

// 下一步
const nextStep = () => {
  if (!validateCurrentStep()) {
    return
  }
  
  if (currentStep.value < steps.length - 1) {
    currentStep.value++
  }
}

// 上一步
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// BPMN设计器相关方法
const openBpmnDesigner = () => {
  bpmnDesignerVisible.value = true
}

const handleBpmnSave = (xml: string) => {
  formData.modelXml = xml
  console.log('流程设计已保存')
}

const toggleXmlPreview = () => {
  showXmlPreview.value = !showXmlPreview.value
}

// 处理提交
const handleSubmit = () => {
  if (!validateBasicInfo()) {
    return
  }
  
  emit('submit', { 
    ...formData,
    variables: JSON.stringify(formData.variables)
  })
}

// 处理关闭
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}
</script>

<style scoped>
.definition-form-wizard {
  padding: 10px 0;
}

/* 步骤导航样式 */
.steps-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 40px;
  padding: 0 20px;
}

.step-item {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  position: relative;
}

.step-item:not(:last-child)::after {
  content: '';
  position: absolute;
  top: 20px;
  left: 100%;
  width: 100%;
  height: 2px;
  background: #e8e8e8;
  z-index: 0;
}

.step-item.completed:not(:last-child)::after {
  background: #1890ff;
}

.step-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e8e8e8;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 600;
  flex-shrink: 0;
  z-index: 1;
  position: relative;
}

.step-item.active .step-number {
  background: #1890ff;
  color: white;
}

.step-item.completed .step-number {
  background: #52c41a;
  color: white;
}

.step-info {
  flex: 1;
  min-width: 0;
}

.step-title {
  font-size: 14px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.step-item.active .step-title {
  color: #1890ff;
}

.step-description {
  font-size: 12px;
  color: #999;
}

/* 步骤内容样式 */
.step-content {
  min-height: 400px;
  padding: 0 20px;
}

.step-panel {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.panel-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
}

/* 表单样式 */
.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-item.full-width {
  flex: 1 1 100%;
}

.form-label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-label.required::after {
  content: ' *';
  color: #ff4d4f;
}

/* 流程变量样式 */
.variables-container {
  background: #fafafa;
  border-radius: 8px;
  padding: 20px;
}

.variables-header {
  margin-bottom: 16px;
}

.variables-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.variable-item {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  padding: 16px;
}

.variable-fields {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1.5fr auto;
  gap: 12px;
  align-items: start;
}

.variable-field {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.variable-field label {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.variable-actions {
  display: flex;
  align-items: flex-end;
  padding-bottom: 6px;
}

.empty-variables {
  text-align: center;
  padding: 40px;
  color: #999;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.empty-variables i {
  font-size: 2rem;
  color: #ccc;
}

/* BPMN设计器样式 */
.bpmn-designer-container {
  background: #fafafa;
  border-radius: 8px;
  padding: 20px;
}

.designer-toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e8e8e8;
}

.designer-preview {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.designer-placeholder {
  text-align: center;
  color: #999;
}

.designer-placeholder p {
  margin: 12px 0;
  font-size: 14px;
}

.placeholder-hint {
  font-size: 12px;
  color: #ccc;
}

.designer-success {
  text-align: center;
  color: #52c41a;
}

.designer-success p {
  margin: 12px 0;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.success-hint {
  font-size: 13px;
  color: #999;
  max-width: 400px;
}

.xml-preview {
  width: 100%;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  margin: -40px -40px 16px -40px;
}

.preview-header h4 {
  margin: 0;
  font-size: 14px;
  color: #333;
}

.xml-editor {
  width: 100%;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  padding: 16px;
  background: #f9f9f9;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  gap: 12px;
}

/* 表单组件样式覆盖 */
:deep(.p-inputtext),
:deep(.p-inputnumber),
:deep(.p-dropdown),
:deep(.p-inputtextarea) {
  height: 40px;
  font-size: 14px;
}

:deep(.p-inputtextarea) {
  height: auto;
  min-height: 120px;
}

:deep(.p-inputnumber .p-inputtext) {
  height: 40px;
}

:deep(.p-error) {
  font-size: 12px;
  margin-top: 4px;
}

/* 小尺寸输入框 */
:deep(.p-inputtext.p-inputtext-sm),
:deep(.p-dropdown.p-dropdown-sm) {
  height: 36px;
  font-size: 13px;
}

/* 下拉框选项字体样式 */
:deep(.p-dropdown-panel .p-dropdown-items .p-dropdown-item) {
  font-size: 14px !important;
  line-height: 20px !important;
  padding: 8px 12px !important;
}

/* 下拉框placeholder样式 */
:deep(.p-dropdown .p-dropdown-label.p-placeholder) {
  font-size: 14px !important;
  line-height: 20px !important;
  color: #6c757d !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .steps-container {
    flex-direction: column;
    gap: 20px;
  }
  
  .step-item:not(:last-child)::after {
    display: none;
  }
  
  .variable-fields {
    grid-template-columns: 1fr;
  }
}
</style>
